<template>
  <div class="questClass-box">

  <!--  <Table
      :tableData="tableData"
      :inits="tableinits"
      canSelect
      :operation="operationinits">
      <template slot-scope="rowScope">
        <el-button @click="edit(rowScope)" type="text" size="small">编辑</el-button>
        <el-button @click="del(rowScope)" type="text" size="small">删除</el-button>
      </template>
    </Table> -->
    <!-- 分页器 S -->
		<el-row style='max-height:800px'>
			<el-col :span='7' style='border-right: 1px solid #e6e6e6;'>
				<el-tree
				:data='tableData'
				node-key='id'
				style='padding:10px'
				@node-click='treeactive'
				default-expand-all
				:expand-on-click-node='false'
				>
					<span class='custom-tree-node' slot-scope='{node,data}'>
						<span>{{data.name}}</span>
							<span>
							<el-button
							type='text'
							size='mini'
							@click.stop='append(data)'>新增</el-button>
							<el-button
							type='text'
							size='mini'
							@click.stop='editor(data)'>编辑</el-button>
							<el-button
							type='text'
							size='mini'
							v-if='!data.children'
							@click.stop='dele(data)'>删除</el-button>
						</span>
					</span>
				</el-tree>
			</el-col>
			<el-col :offset='1' :span='16'>
					<el-row >
					<el-col :span="3"><el-button @click="multiDel">删除</el-button></el-col>
					<el-col :span="3"><el-button @click="add_user_show=true;userdata=JSON.parse(JSON.stringify(new_userdata))" >新增</el-button></el-col>
					<el-col :span="3"><el-button @click="() => {this.dialogVisible = true}">导入</el-button></el-col>
					<el-col :span="3"><el-button @click="dc"><a :href="exportUrlupname" class="upload_te">导出</a></el-button></el-col>
					<el-col :span='12'  :push='1'>
						<el-col :span='12' :push='1'>
							<el-input placeholder='请输入用户姓名' v-model='key_word_user'></el-input>
						</el-col>
						<el-col :span='3' :push='2' style='text-align: right;'>
							<el-button @click='search_user'>查询</el-button>
						</el-col>
					</el-col>
				</el-row>

				<el-table
				:data='user_list'
				border
				@selection-change='_mixSelectionChange'>
					<el-table-column type='selection' width='55px' align='center'></el-table-column>
					<template v-for='item in tableinits'>
						<el-table-column :prop='item.prop' :label='item.label' align='cneter'></el-table-column>
					</template>
					<el-table-column label='状态'>
						<template slot-scope='scope'>
							<span>{{status[scope.row.status]}}</span>
						</template>
					</el-table-column>
					<el-table-column label='类型'>
						<template slot-scope='scope'>
							<span>{{typename[scope.row.type]?typename[scope.row.type]:'学员'}}</span>
						</template>
					</el-table-column>
					<el-table-column label='操作'>
						<template slot-scope='scope'>
							<el-button type='text' @click='edit_user(scope.row)'>编辑</el-button>
							<el-button type='text' @click='reset(scope.row)'>重置密码</el-button>
						</template>
					</el-table-column>
				</el-table>


				<el-row style='text-align: right;margin-top: 15px;'>
					<el-pagination
						layout="prev, pager, next"
						:page-size="15"
						:current-page="pageNo"
						:total="total"
						@current-change="pageNoChange">
					</el-pagination>
				</el-row>
			</el-col>
		</el-row>

  <!--  <el-row>
      <el-col>
        <el-pagination
          layout="prev, pager, next"
          :page-size="15"
          :current-page="pageNo"
          :total="total"
          @current-change="pageNoChange">
        </el-pagination>
      </el-col>
    </el-row> -->
    <!-- 分页器 E -->

		<el-dialog :visible='add_user_show' :title='dialog_title' @close='add_user_show=false' width='40%'>
			<el-form :model='userdata' label-width='100px' ref='dialog_form'>
				<el-form-item prop='name' label='登录名' :rules='{required:true,message:"该项必填"}'>
					<el-input v-model='userdata.name'></el-input>
				</el-form-item>
				<el-form-item prop='name' label='姓名' :rules='{required:true,message:"该项必填"}'>
					<el-input v-model='userdata.username'></el-input>
				</el-form-item>
				<el-form-item prop='name' label='类型' :rules='{required:true,message:"该项必填"}'>
					<el-select v-model='userdata.type'>
						<el-option v-for='item in usertype' :label='item.text' :value='item.type' :key='item.type'></el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop='name' label='手机号' >
					<el-input v-model='userdata.mobile'></el-input>
				</el-form-item>
				<el-form-item prop='name' label='电子邮箱' >
					<el-input v-model='userdata.email'></el-input>
				</el-form-item>
			</el-form>
			<el-row style='margin-top:10px;text-align: center;'>
				<el-button @click='user_submit("dialog_form")' type='primary'>保存</el-button>
			</el-row>
		</el-dialog>



		<el-dialog
      title="导入人员"
      :visible.sync="dialogVisible"
      width="44%"
      :before-close="closeHandle">

       <el-upload
					  class="upload-demo"
					  drag
					  ref="upload"
					  :action="exportUrldowname"
					  :show-file-list="false"
					  :on-success="handSuccess"
		        :on-remove="handleRemove"
		        :file-list="fileList"
		        :before-upload="beforeAvatarUpload"
            :on-progress="uploadProgress"
            :disabled="uploading"
					  multiple>
					  <i :class="[uploading ? 'el-icon-loading' : 'el-icon-upload']"></i>

            <div v-if="uploading" class="el-upload__text">正在导入，请等待</div>
					  <div v-else class="el-upload__text">将文件拖到此处，或<em>点击上传<p></p></em></div>

					  <div class="el-upload__tip tishi" slot="tip" v-show="ok">共上传 {{sum}} 行，成功上传 {{succes}} 行，更新 {{update}} 条</div>

					</el-upload>
					<a :href="exportUrlupwnamemb" class="Download_te">下载模板</a>
	      			<el-table v-show="ok"
						      :data="retureData"
						      style="width: 100%"
                  :height="250"
                  size="small">
						      <el-table-column
						        prop="row"
						        label="错误行数"
						        width="180">
						      </el-table-column>
						      <el-table-column
						        prop="error"
						        label="错误原因">
						      </el-table-column>
						</el-table>

    </el-dialog>
    <!-- 导入弹窗 E -->
  </div>
</template>

<script>
import Table from '@/components/Table'
import { quest_fmt_getDepManage } from '@/util/dataFMT'
import { FILE_UPLOAD_LIMIT } from '@/global_Init'
import multidel from '@/mixins/multidel'
let status = {active:"正常",delete:'删除'};
let typename = {admin:'管理员',visitor:'访客',vendor:'供应商'}
export default {
  name: 'DepManage',
  components: {
    Table
  },
  mixins: [multidel],
  mounted () {
//     this.$API.getDepManage()
//     .then(data => {
//       this.total = data.total
//       this.tableData = 	this.settree(data.data)
// 			console.log(this.tableData)
//     })
//     .catch(errmsg => {
//       console.log(errmsg)
//     })
  },
	created(){
		this.gettreedata();
			var user_info =JSON.parse(localStorage.getItem('userinfo'));  //个人信息
    this.saas_user_id=user_info.saas_user_id;
	},
  data () {
    return {
      uploading: false,
			key_word_user:'',
			status,
			typename,
			add_user_show:false,
			dialog_title:'新增人员',
      total: 0,
      pageNo: 1,
			usertype:[{type:'admin',text:'管理员'},{type:'trainee',text:'学员'},{type:"visitor",text:'访客'},{type:"vendor",text:'供应商'}],
			user_list:[],
			dept_id:'',
			new_userdata:{
				name:"",
				username:"",
				type:'',
				mobile:"",
				email:""
			},
			userdata:{},
			tables:[],
      tableData: [],
      tableinits: [
        { label: '登录名',  prop: 'name' },
        { label: '姓名', prop: 'username' },
      ],
      sum:'',
      succes: '',
      update: '',
      saas_user_id:'',
      ok:false,
      fileList: [],
      retureData:[{row:'',error:''}],
      dialogVisible: false,
    }
  },
	computed:{
		_disabled(){
			return this.tables.length
		},
		  exportUrlupname() {
      return `${EHS.HOST}/api/v1/export/user?saas=${this.saas_user_id}`
    },
     exportUrldowname() {
      return `${AOSAIBAN.HOST}/api/v1/import/user`
    },
     exportUrlupwnamemb() {
      return `${EHS.HOST}/api/v1/import/template/user`
    }

	},

  methods: {
    multiDel () {
      this._mixMutiDel(`delUser`, () => {
        this.pageNoChange(1)
      })
    },
    closeHandle (done) {
      console.log(this.uploading)
      if (!this.uploading) {
        done()
      }
    },
    uploadProgress () {
      if (!this.uploading) {
        this.uploading = true
      }
    },
		search_user(){
			// 人员搜索
		this.getuserdata({keyword:this.key_word_user})
		},
		edit_user(data){
			this.add_user_show=true;
			this.userdata = JSON.parse(JSON.stringify(this.new_userdata));
			this.$API.getOneUser(data.id).then(res=>{
				this.userdata = res
			})
		},
		reset(data){
			this.$prompt('请输入密码','重置密码',{
				inputPattern:/.{6,}/,
				inputErrorMessage:"不能少于6位数"
			}).then(res=>{
				this.$API.resetPassword(data.id,{password:res.value}).then(res=>{
					this.$message.success('修改成功')
				})
			}).catch(err=>{})
		},
		user_submit(name){
			this.$refs[name].validate(valid=>{
				if(valid){
					if(this.userdata.id){
						this.$API.editorUser(this.userdata.id,this.userdata).then(res=>{
							this.$message.success('修改成功')
							this.add_user_show=false;
							this.pageNoChange(1)
						})
					}else{
						this.userdata.dept_id = this.dept_id;
					this.$API.DepUserAdd(this.userdata).then(res=>{
						this.$message.success('创建成功')
						this.add_user_show=false;
						this.pageNoChange(1)
					})
					}
				}
			})
		},
		table_select(data){
			this.tables=data
		},
		pageNoChange(index){
			let form = {
				page:index,
				department:this.dept_id
			}
			this.pageNo = index;
			this.getuserdata(form)
		},
		getuserdata(form){
			this.$API.getUserManage(form).then(res=>{
				this.total = res.total;
				this.user_list = res.data;
			})
		},
		treeactive(data,node){
			let form = {
				page:this.pageNo,
				department:data.id
			}
			this.dept_id = data.id
			this.getuserdata(form)
		},
		append(data){
			let _this = this
			this.$prompt('请输入新增部门名称','名称',{
				inputErrorMessage:'名称不能为空',
				inputPattern:/.{1,}/
			}).then(res=>{
				let params = {
					name:res.value,
					parent_id:data.id
				}
				_this.$API.DepAdd(params).then(res=>{
					this.$message.success('添加成功')
					_this.gettreedata()
				})
			})
		},
		editor(data){
			let _this = this;
			this.$prompt('修改部门名称','修改',{
				inputValue:data.name,
				inputErrorMessage:'名称不能为空',
				inputPattern:/.{1,}/
			}).then(res=>{
				console.log(res.value)
				data.name = res.value
				_this.$API.setDepName(data.id,data).then(res=>{
					_this.$message.success('修改成功');
					_this.gettreedata()
				})

			})
		},
		dele(data){
			this.$confirm(`确认要删除${data.name}?`,'提示').then(res=>{
				this.$API.DepDel(data.id).then(res=>{
					this.gettreedata()
					this.$message.success('删除成功')
				}).catch(re=>{})
			})

		},
		settree(data){
			let fa = (da) =>{
				let children = [];
				data.forEach(item=>{
					if(da.id == item.parent_id){
						children.push(fa(item))
					}
				})
				if(children.length){da.children=children}
				return da
			}
			let re = []
			data.forEach(item=>{
				if(item.parent_id === 0){
					re.push(fa(item))
				}
			})
			return re
		},
    gettreedata () {
      this.$API.getDepManage()
      .then(data => {
        this.tableData = 	this.settree(data)
      })
    },
    edit (scope) {
      console.log(scope)
      this.$message.info({
        message: `编辑按钮被按下`
      })
    },
    del (scope) {
      console.log(scope)
      this.$message.info({
        message: `删除按钮被按下`
      })
    },
    add () {
      this.$prompt('题库分类名称', '新增', {
        confirmButtonText: '保存',
        inputPattern: /.{1,}/,
        inputErrorMessage: '名称不能为空'
      }).then(({ value }) => {
        this.$API.addDepManage(value)
        .then(data => {
          this.pageNoChange(1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    handleClose () {
      console.log(`dialog closed`)
      this.dialogVisible = false;
      this.retureData=[{row:'',error:''}];
      this.ok=false;
    },
    submit () {
      console.log(`submit clicked`)
      // this.submitUpload();
      this.dialogVisible = false;
      this.$refs.upload.submit();
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handSuccess(response, file, fileList){
    	console.log(response)
    	this.retureData=response.data.errors;
    	this.sum=response.data.total;
    	this.update=response.data.total;
    	this.succes=response.data.success;
    	let mess="共上传 " +this.sum +" 行，成功上传 "+ this.succes +" 行,更新 "+ this.update +" 条";
    	console.log(mess)
    	if(response.data.total!=response.data.success){this.ok=true;}
    	else{
    		this.$message({type:'success', message: mess,duration:5000});
    		this.$message.success(`上传文件成功`);
    	}
      this.$nextTick(() => {this.uploading = false})
    },
    handlePreview(file) {
      console.log(file);
    },
     beforeAvatarUpload(file) {
      console.log(file);
      console.log(file.name)
      let isture=false;
      if(file.name.match(/\.(xlsx|xls|xlsm|csv)$/i)){isture=true;}
//    const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < FILE_UPLOAD_LIMIT;

        if (!isture) {
        	 this.$refs.upload.abort();
          this.$message.error('上传文件只能是 Excel 文件!');

        }
        if (!isLt2M) {
          this.$message.error(`上传文件大小不能超过 ${FILE_UPLOAD_LIMIT}MB!`);
        }
       return isture && isLt2M;
				// return isture;
 		 },
 		 dc () { // 导出按钮被按下

    }
  }
}
</script>

<style>
 .questClass-box {
   text-align: left;
   width: 100%;
   overflow: hidden;
 }
 .custom-tree-node{
	 width: 100%;
	 display: flex;
	 flex-flow: row nowrap;
	 justify-content: space-between;
	 font-size: 14px;
	 align-items: center;
 }
 .el-tree-node{
	 padding: 5px 0;
 }
   .Download_te{float: right;color: #0366bb ;text-decoration: none;}
  .Download_te:hover{text-decoration: underline;}
  .upload_te{color: #606266 !important;text-decoration: none;}
  .upload-demo {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
  .upload-demo .el-icon-loading{
    font-size: 30px;
    margin-top: 60px;
  }
</style>
